package com.example.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.common.Result;
import com.example.demo.entity.Book;
import com.example.demo.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;

@Api(tags = "书籍管理")
@RestController
@RequestMapping("/api/book")
public class BookController {

    @Resource
    private BookService bookService;

    @ApiOperation("新增书籍")
    @PostMapping("/add")
    public Result<Void> add(@RequestBody Book book) {
        bookService.save(book);
        return Result.success(null, "新增成功");
    }

    @ApiOperation("删除书籍")
    @PostMapping("/delete/{id}")
    public Result<Void> delete(@ApiParam("书籍ID") @PathVariable Long id) {
        bookService.removeById(id);
        return Result.success(null, "删除成功");
    }

    @ApiOperation("修改书籍")
    @PostMapping("/update")
    public Result<Void> update(@RequestBody Book book) {
        bookService.updateById(book);
        return Result.success(null, "修改成功");
    }

    @ApiOperation("分页列表查询")
    @GetMapping("/list")
    public Result<IPage<Book>> list(@RequestParam int pageNum, @RequestParam int pageSize) {
        return Result.success(bookService.pageQuery(pageNum, pageSize));
    }

    @ApiOperation("条件分页查询")
    @GetMapping("/search")
    public Result<IPage<Book>> search(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String publisher,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String author,
            @RequestParam int pageNum,
            @RequestParam int pageSize) {
        LocalDate start = (startDate != null && !startDate.isEmpty()) ? LocalDate.parse(startDate) : null;
        LocalDate end = (endDate != null && !endDate.isEmpty()) ? LocalDate.parse(endDate) : null;
        return Result.success(bookService.search(name, publisher, start, end, author, pageNum, pageSize));
    }
} 